<template>
  <div class="flowpath-container">
    <div>
      <div class="mb20">
        <span class="color_494949 ft12 pr5 ml10">{{ translate('关键字') }}：</span>
        <el-input
          v-model="keywords"
          class="w192 mr10"
          :placeholder="translate('请输入物料编码或名称')"
        />
        <span class="color_494949 ft12 pr5">{{ translate('用料单位') }}：</span>
        <el-autocomplete
          v-model="searchInfo"
          class="inline-input mr10"
          :fetch-suggestions="querySearch"
          placeholder="选择单位"
          @select="handleSelect"
        />
        <span class="color_494949 ft12 pr5 ml10">{{ translate('发料单号') }}：</span>
        <el-input
          v-model="searchInfo1"
          class="w192 mr10"
          :placeholder="translate('请输入发料单号')"
        />
        <span class="color_494949 ft12 pr5">{{ translate('领料单号') }}：</span>
        <el-input
          v-model="searchInfo3"
          class="w192 mr10"
          :placeholder="translate('请输入领料单号')"
        />
        <span class="color_494949 ft12 pr5 w70">{{ translate('审核状态') }}：</span>
        <el-select
          v-model="Remark"
          class="w192 mr10"
          :placeholder="translate('请选择')"
         >
          <el-option
            v-for="item in RemarkArry"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
          </el-select>
        <div class="mt10 ml10">
          <span class="color_494949 ft12 pr5">{{ translate('创建时间') }}：</span>
          <el-date-picker
                v-model="searchInfo2"
                end-placeholder="结束日期"
                range-separator="至"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD"
              />
            <el-button class="settingBtn ml10" type="primary" @click="getList">
              {{ translate('查询') }}
            </el-button>
            <el-button class="settingBtn ml10" type="primary" @click="resetFn()">
              {{ translate('重置') }}
            </el-button>
        </div>
      </div>
      <div class="add">
        <el-button
          v-if="MenuAuths('add')"
          class="settingBtn"
          type="primary"
          @click="addFn"
          plain
        >
          {{ translate('新增') }}
        </el-button>
        <el-upload
          accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
          :action="action"
          :before-upload="beforeUpload"
          class="ml-upload"
          :headers="headers"
          name="fileInput"
          :on-error="handleError"
          :on-success="handleSuccess"
          :show-file-list="false"
        >
          <ElButton type="primary" @click="uploadFn()" plain>
            {{ translate('导入') }}
          </ElButton>
        </el-upload>
        <el-button type="primary" @click="exportFn()" plain>
                    {{ translate('导出') }}
        </el-button>
        <el-button
          class="settingBtn"
          type="primary"
          @click="batchFn"
          plain
        >
          {{ translate('批量审核') }}
        </el-button>
      </div>
      <el-table v-loading="loading"
                :data="tableData"
                :row-class-name="tableRowClassName"
                :row-key="getRowKey"
                @selection-change="handleSelectionChange"
                @row-dblclick="dblclickFn">
        <el-table-column prop="value" type="selection" width="55" />
        <!-- <el-table-column label="序号" type="index" width="80" /> -->
        <el-table-column
          :label="translate('部门')"
          prop="DepartmentName"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('发料单号')">
          <template #default="{ row }">
            <div>
              <span class="iconcolor" @click="print(row)">{{ row.Code }}</span>
              <vab-icon icon="file-copy-line" @click="copyToClipboard(row.Code)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('领料单号')"
          prop="SourceBillNo"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('编制单位')"
          prop="DepartmentName"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('出库类型')">
          <template #default="{ row }">
            <div>{{ row.OBType === '1' ? translate('委托仓储出库') : '' }}</div>
          </template>
        </el-table-column>
        <el-table-column :label="translate('用料单位')" prop="POUnit" />
        <el-table-column
          :label="translate('发料库点')"
          prop="WHName"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('发料日期')"
          prop="DeliveryDate"
          show-overflow-tooltip
        />
        <el-table-column
          :label="translate('创建日期')"
          prop="CreateDate"
          show-overflow-tooltip
          width="170"
        />
        <el-table-column
          :label="translate('提货单位')"
          prop="POUnit"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('审核状态')">
          <template #default="{ row }">
            <div>
              <el-tag type="success" v-if="row.ReceiveStatus === '已审核'">{{ row.ReceiveStatus }}</el-tag>
              <el-tag type="info" v-if="row.ReceiveStatus && row.ReceiveStatus !== '已审核'">{{ row.ReceiveStatus }}</el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          :label="translate('创建人')"
          prop="CreateUserName"
          show-overflow-tooltip
        />
        <el-table-column :label="translate('操作')" width="400">
          <template #default="{ row }">
            <el-button plain size="small" type="primary" @click="examineFn(row)">
              {{ translate('审核') }}
            </el-button>
            <el-button
              plain
              size="small"
              type="primary"
              @click="outexamineFn(row)"
            >
              {{ translate('反审') }}
            </el-button>
            <el-button
              v-if="MenuAuths('edit')"
              plain
              size="small"
              type="primary"
              @click="detailFn(row)"
              :disabled="row.ReceiveStatus==='已作废'?true:false"
            >
              {{ translate('编辑') }}
            </el-button>
            <el-button plain size="small" type="primary" @click="print(row)" :disabled="row.ReceiveStatus==='已作废'?true:false">
              {{ translate('打印') }}
            </el-button>
            <el-button plain size="small" type="primary" @click="ZFFn(row)">
              {{ translate('作废') }}
            </el-button>
            <el-button
              v-if="MenuAuths('delete') && row.ReceiveStatus !== '已审核'"
              plain
              size="small"
              type="danger"
              @click="deletedFn(row)"
            >
              {{ translate('删除') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
          background
          :current-page="pageNo"
          :layout="layout"
          :page-size="pageSize"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="dialogVisible"
      :title="translate('物资发料单详情')"
      width="1250px"
      @close="closeFn"
      :close-on-click-modal="false"
    >
      <i v-if="status === 1" class="iconfont icon-shenhezhong iconcommon"></i>
      <i v-if="status === 2" class="iconfont icon-yishenhe iconcommon2"></i>
      <img src='' />
      <detail
        :agreementlist="agreementList"
        :chileddetail="chileddetail"
        :form="form"
        :fromtype="submitType"
        :pickorderdata="pickOrderDataList"
        :whdata="WHdata"
        @changelist="changeList"
        @deletedchild="deletedchild"
      />
      <template #footer>
        <el-button @click="dialogVisible = false">
          {{ translate('取消') }}
        </el-button>
        <el-button :disabled="isclick" type="primary" @click="submit">
          {{ translate('确定') }}
        </el-button>
      </template>
    </el-dialog>
    <!-- 打印页面 -->
    <el-dialog v-model="isPrint" center width="78%" @close="isPrint = false" :close-on-click-modal="false">
      <print
        ref="tableRef"
        :chileddetail="chileddetail"
        :form="form"
        fromprint="arrivalConfirm"
      />
      <template #footer>
        <el-button @click="isPrint = false">{{ translate('取消') }}</el-button>
        <el-button type="primary" @click="submitPrint">
          {{ translate('打印') }}
        </el-button>
      </template>
    </el-dialog>
    <wordflow
      :drawershow="isdrawershow"
      :formcode="formCode"
      :formid="formId"
      @handclose="handleClose"
    />
  </div>
</template>

<script>
  import {
    OutboundBillData,
    DelOutboundBill,
    UpdateOutboundBill,
    AddOutboundBill,
    OutboundBillDetail,
    agreePageData,
    pickOrderData,
    startflow,
    getinstance,
    WHGetPageData,
    OutboundCancel,
    OutboundExamine,
    OutboundBatchData,
    OutboundCheckPrint,
    OutboundVoid,
    ExportOutBill,
  } from '@/api/form'
  import { BaseGetPageData } from '@/api/item'
  import detail from './components/detail'
  import wordflow from '@/views/components/wordflow/index'
  import { MenuAuth } from '~/src/utils/permission'
  import VabPrint from '@/plugins/VabPrint'
  import print from './components/print'
  import { translate } from '@/i18n'
  import { useUserStore } from '@/store/modules/user'
  import { baseURL } from '@/config'
  import { parseTime } from '@/utils'
  const { token } = useUserStore()
  export default defineComponent({
    name: 'Arrival',
    components: { detail, print, wordflow },
    data() {
      return {
        tableData: [],
        searchInfo: '',
        searchInfo1: '',
        searchInfo2: [],
        wheres: '',
        total: 0,
        pageNo: 1,
        pageSize: 20,
        loading: true,
        dialogVisible: false,
        enabled: 0,
        DetailPageData: {},
        chileddetail: [],
        submitType: 'add',
        agreementList: [],
        layout: 'total, sizes, prev, pager, next, jumper',
        deleList: [],
        keywords: '',
        OBMId: '',
        MenuAuths: '',
        pickOrderDataList: [],
        isPrint: false,
        isdrawershow: false,
        formId: '',
        formCode: 'Wms_OutboundBillMaster',
        status: -1,
        translate: translate,
        action: '',
        headers: '',
        isclick: false,
        searchInfo3: '',
        Remark: '全部',
        selectArr: [],
        isdisable: false,
        SupplierData: [],
        form: {
          Code: '',
          FullName: '',
          OBNo: '',
          OBType: '',
          POUnit: '',
          ProName: '',
          CProName: '',
          CustomNo: '',
          WHName: '',
          LCNo: '',
          CarNum: '',
          Receiver: '',
          ReceiveStatus: '',
          DeliveryDate: '',
          TotalWeight: '',
          TotalSafeAmt: '',
          TotalPackAmt: '',
          TotalCheckAmt: '',
          TotalAmt: '',
          Remark: '',
          SourceBillNo: '',
        },
        RemarkArry: [
          {
            label: '全部',
            value: '全部'
          },
          {
            label: '已审核',
            value: '已审核'
          },
          {
            label: '未审核',
            value: '未审核'
          },
          {
            label: '已反审核',
            value: '已反审核'
          },
          {
            label: '已作废',
            value: '已作废'
          }
        ],
      }
    },
    watch: {
      isPrint(val) {
        if (val) {
          document.title = '中国石油青海油田公司发料单'
        } else {
          document.title = '物资出库单'
        }
      },
    },
    created() {
      this.MenuAuths = MenuAuth
      this.searchInfo = sessionStorage.getItem('FLsearchInfo') || ''
      this.searchInfo1 = sessionStorage.getItem('FLsearchInfo1') || ''
      this.searchInfo3 = sessionStorage.getItem('FLsearchInfo3') || ''
      this.searchInfo2 = [this.getFirstDayOfMonthFormatted(),this.getLastDayOfMonth()]
      this.Remark = sessionStorage.getItem('FLRemark') || ''
      this.getList()
      this.BaseGetPageData()
    },
    methods: {
      getLastDayOfMonth() {
      // 创建一个当前日期的副本
          let date = new Date();

          // 设置日期为下个月的第一天（这样可以跳过本月所有日期）
          date.setDate(1);
          date.setMonth(date.getMonth() + 1);
          date.setDate(0); // 这会将日期设置为上一个月的最后一天

          // 格式化日期为 YYYY-MM-DD
          let year = date.getFullYear();
          let month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的，所以要加1
          let day = String(date.getDate()).padStart(2, '0');

          return `${year}-${month}-${day}`;
      },
      getFirstDayOfMonthFormatted() {
            const today = new Date(); // 获取当前日期
            const year = today.getFullYear(); // 获取年份
            const month = today.getMonth(); // 获取月份（注意：0表示1月，11表示12月）
            const date = 1; // 设置日期为1（即当前月份的第一天）

            // 创建日期对象
            const firstDay = new Date(year, month, date);

            // 手动格式化日期为 YYYY-MM-DD
            const formattedDate = `${year.toString().padStart(4, '0')}-${(month + 1).toString().padStart(2, '0')}-${date.toString().padStart(2, '0')}`;
            return formattedDate;
        },
      //复制标识
      async copyToClipboard(val) {
        if (navigator.clipboard && window.isSecureContext) {
          try {
          console.log(navigator.clipboard)
          console.log(window.isSecureContext)
          await navigator.clipboard.writeText(val)
          this.$message({
            message:'复制成功',
            type:'success',
          })
          } catch (err) {
            this.$message({
            message:'复制失败',
            type:'error',
          })
          }

        }else {
          // 创建text area
        const textArea = document.createElement("textarea")
        textArea.value = val
        // 使text area不在viewport，同时设置不可见
        textArea.style.position = "absolute"
        textArea.style.opacity = 0
        textArea.style.left = "-999999px"
        textArea.style.top = "-999999px"
        document.body.appendChild(textArea)
        textArea.focus()
        textArea.select()

        return new Promise((res, rej) => {
          // 执行复制命令并移除文本框
          document.execCommand("copy") ? res() : rej()
          textArea.remove()
        }).then(() => {
          this.$message({
              message: "复制成功",
              type: "success",
            })
          }).catch((err) => {
            this.$message({
              message: "复制失败",
              type: "error",
            })
          })
        }

      },
      async dblclickFn(row) {
        this.deleList = []
        this.form = row
        this.OBMId = row.OBMId
        this.submitType = 'edit'
        await this.getinstances(row)
        await this.OutboundBillDetail()
        await this.agreePageData()
        await this.pickOrderDatas()
        this.dialogVisible = true
      },
      batchFn() {
        if(this.selectArr.length<=0){
          this.$message({
            message: translate('请选择要审核的单据'),
            type: 'warning',
          })
          return
        }else {
          console.log(this.selectArr)
          this.outboundBatch()
        }
      },
      async outboundBatch() {
        const formIdArr = []
        this.selectArr.map((item,index) =>{
             formIdArr.push(
              {
                formId: item.OBMId
              }
             )
        })
        const params = formIdArr
        const data = await OutboundBatchData(params)
        if(data.result.code === '200'){
          this.$message({
            message: translate('已提交审核'),
            type: 'success',
          })
          this.getList()
        }else {
          this.$message({
            message: data.result.message,
            type: 'error',
          })
        }
        console.log(data)
      },
      async uploadFn() {
        this.headers = this.headers = {
          Authorization: `Bearer ${token}`,
        }
        this.action = `${baseURL}/Wms_OutboundBillMaster/ImportNew`
      },
      handleError(data) {
        console.log(data)
      },
      handleSuccess(data) {
        console.log(data)
        if (data.code === '200') {
          this.$message({
            type: 'success',
            message: data.message,
          })
          this.getList()
        } else {
          this.$message({
            message: data.message,
            type: 'error',
          })
        }
      },
      handleClose() {
        this.isdrawershow = false
      },
      async print(row) {
        this.form = row
        this.OBMId = row.OBMId
        await this.OutboundCheckPrints()
      },
      async OutboundCheckPrints() {
          const params ={
                formId: this.OBMId
          }
          const data = await OutboundCheckPrint(params)
          if(data.result.code === '200') {
            await this.OutboundBillDetail()
            this.isPrint = true
          }
      },
      async submitPrint() {
        document.title = '中国石油青海油田公司发料单'
        await VabPrint(this.$refs.tableRef)
        this.isPrint = false
      },
      changeList(val) {
        this.chileddetail = val?.Detail
        this.form = {
          Code: val.Code,
          FullName: val.FullName,
          OBNo: val.OBNo,
          OBType: val.OBType,
          POUnit: val.POUnit,
          ProName: val.ProName,
          CProName: val.CProName,
          CustomNo: val.CustomNo,
          WHName: val.WHName,
          LCNo: val.LCNo,
          CarNum: val.CarNum,
          Receiver: val.Receiver,
          ReceiveStatus: val.ReceiveStatus,
          DeliveryDate: val.DeliveryDate,
          TotalWeight: val.TotalWeight,
          TotalSafeAmt: val.TotalSafeAmt,
          TotalPackAmt: val.TotalPackAmt,
          TotalCheckAmt: val.TotalCheckAmt,
          TotalAmt: val.TotalAmt,
          Remark: val.Remark,
          SourceBillNo: val.PONo,
        }
      },
      async outexamineFn(row) {
          this.formId = row.OBMId
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_OutboundBillMaster',
              type: 'fsh',
              statusSH: row.ReceiveStatus
            },
        })
        // const params = {
        //   formId: row.OBMId,
        // }
        // const data = await OutboundCancel(params)
        // this.getList()
        // this.$message({
        //   message: data.result.message ? data.result.message : '未知错误',
        // })
      },
      async BaseGetPageData() {
        const params = {
          pageNo: 1,
          pageSize: 100,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await BaseGetPageData(params)
        if (data.data.rows && data.data.rows.length > 0) {
          data.data.rows.map((item) => {
            item.value = item.FullName
          })
        }
        this.SupplierData = data.data.rows
      },
      querySearch(queryString, cb){
        const restaurants = this.SupplierData
        const results =
          queryString && queryString != 'null'
            ? restaurants.filter(createFilter(queryString))
            : restaurants
        console.log(results)
        // 调用 callback 返回建议列表的数据
        cb(results)
      },
    createFilter(queryString){
      return (restaurant) => {
        console.log(restaurant)
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
      }
    },
      async ZFFn(row) {
        this.formId = row.OBMId
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_OutboundBillMaster',
              type: 'zf',
              statusSH: row.ReceiveStatus
            },
        })
        // this.$confirm(translate('确认作废吗?'), translate('提示'), {
        //   confirmButtonText: translate('确定'),
        //   cancelButtonText: translate('取消'),
        //   type: 'warning',
        // })
        //   .then(() => {
        //     this.OutboundVoids(row)
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: 'info',
        //       message: translate('已取消'),
        //     })
        //   })
      },
      async OutboundVoids(row) {
          const params = {
            formId: row.OBMId
          }
          const data = await OutboundVoid(params)
          if(data.result.code === '200') {
            this.$message({
              message: '操作成功' ,
            })
          }else {
            this.$message({
              message: data.result.message ,
            })
          }
      },
      async examineFn(row) {
        // this.$confirm(translate('确认提交?'), translate('提示'), {
        //   confirmButtonText: translate('确定'),
        //   cancelButtonText: translate('取消'),
        //   type: 'warning',
        // })
        //   .then(() => {
        //     this.OutboundExamines(row)
        //     this.isdisable = true
        //   })
        //   .catch(() => {
        //     this.$message({
        //       type: 'info',
        //       message: translate('已取消删除'),
        //     })
        //   })
        // const params = {
        //   keyValue: row.OBMId,
        //   code: 'Wms_OutboundBillMaster', //row.Code,
        //   formUrl: 'outboundBill',
        //   flowData: null,
        // }
        // const data = await startflow(params)
        // if (data.code === '200') {
          this.formId = row.OBMId
          // this.isdrawershow = true
          this.$router.push({
            path: '/table/detail',
            query: {
              formId: this.formId,
              formcode: 'Wms_OutboundBillMaster',
              statusSH: row.ReceiveStatus
            },
          })
        // } else {
        //   this.$message({
        //     message: data.message,
        //     type: 'error',
        //   })
        // }
      },
      async OutboundExamines(row) {
        const params = {
          code: 'Wms_OutboundBillMaster',
          formId: row.OBMId,
        }
        const data = await OutboundExamine(params)
        if (data.result.code === '200') {
          this.getList()
          this.$message({
            message: translate('提交成功'),
            type: 'success',
          })
          this.isdisable = false
        }else {
          this.$message({
            message: translate(data.result.message),
            type: 'error',
          })
          this.isdisable = false
        }
      },
      resetFn() {
        this.searchInfo = ''
        this.searchInfo1 = ''
        this.searchInfo2 = []
        this.searchInfo3 = ''
        this.Remark = '全部'
        this.pageNo = 1
        this.pageSize = 20
        sessionStorage.removeItem('FLsearchInfo')
        sessionStorage.removeItem('FLsearchInfo1')
        sessionStorage.removeItem('FLsearchInfo2')
        sessionStorage.removeItem('FLsearchInfo3')
        sessionStorage.removeItem('FLRemark')
        this.getList()
      },
      async getList() {
        this.wheres = ''
        if (this.Remark || this.searchInfo || this.searchInfo1 || this.searchInfo3 || (this.searchInfo2 && this.searchInfo2 != [] && this.searchInfo2 != null && this.searchInfo2 !='null')) {
          const arr = []
          this.searchInfo.trim() !== '' &&
            arr.push({
              name: 'POUnit',
              value: this.searchInfo,
              displayType: 'like',
            })
          this.searchInfo1.trim() !== '' &&
            arr.push({
              name: 'Code',
              value: this.searchInfo1,
              displayType: 'like',
            })
          this.searchInfo2 &&
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo2!=null ? this.searchInfo2[0]+' 00:00:00':'',
              displayType: 'ThanOrEqual',
            })
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo2!=null ? this.searchInfo2[1]+' 23:59:59':'',
              displayType: 'LessOrequal',
            })
          this.searchInfo3 &&
            this.searchInfo3.trim() !== '' &&
            arr.push({
              name: 'SourceBillNo',
              value: this.searchInfo3,
              displayType: 'like',
            })
          this.Remark.trim() !== '' &&
            arr.push({
              name: 'ReceiveStatus',
              value: this.Remark === '全部' ? '' : this.Remark,
              displayType: 'like',
            })
          this.wheres = JSON.stringify(arr)
          sessionStorage.setItem('FLsearchInfo', this.searchInfo)
          sessionStorage.setItem('FLsearchInfo1', this.searchInfo1)
          sessionStorage.setItem('FLsearchInfo2', this.searchInfo2)
          sessionStorage.setItem('FLRemark', this.Remark)
          sessionStorage.setItem('FLsearchInfo3', this.searchInfo3)
        }
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: this.wheres,
          export: false,
          value: this.keywords,
        }
        const data = await OutboundBillData(params)
        this.tableData = data.data.rows
        this.total = data.data.total
        console.log(this.tableData)
        this.loading = false
      },
      deletedchild(e) {
        this.deleList = e
        console.log(e)
      },
      deletedFn(row) {
        this.$confirm(translate('确认删除该文件吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            this.deleted(row)
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消删除'),
            })
          })
      },
      async deleted(row) {
        const OBMId = []
        OBMId.push(row.OBMId)
        const params = OBMId
        const data = await DelOutboundBill(params)
        if (data.code == '200') {
          this.$message({
            message: translate('删除成功'),
            type: 'success',
          })
          await this.getList()
        }
      },
      //分页条数切换
      handleSizeChange(val) {
        this.pageSize = val
        this.getList()
      },
      //分页切换
      handleCurrentChange(val) {
        this.pageNo = val
        this.getList()
      },
      tableRowClassName({ row, rowIndex }) {
        row.row_index = rowIndex
      },
      handleSelectionChange(e) {
        this.selectArr = e
      },
      getRowKey(row) {
        return row.OBMId
      },
      async addFn() {
        this.deleList = []
        this.submitType = 'add'
        this.status = -1
        this.form = {
          Code: '',
          FullName: '',
          OBNo: '',
          OBType: '',
          POUnit: '',
          ProName: '',
          CProName: '',
          CustomNo: '',
          WHName: '',
          LCNo: '',
          CarNum: '',
          Receiver: '',
          ReceiveStatus: '',
          DeliveryDate: '',
          TotalWeight: '',
          TotalSafeAmt: '',
          TotalPackAmt: '',
          TotalCheckAmt: '',
          TotalAmt: '',
          Remark: '',
          SourceBillNo: '',
        }
        await this.agreePageData()
        await this.pickOrderDatas()
        await this.WHGetPageData()
        this.chileddetail = []
        this.dialogVisible = true
      },
      async WHGetPageData() {
        const params = {
          pageNo: 1,
          pageSize: 20,
          wheres: `[{"name":"ModuleId","value":"","displayType":"equal"}]`,
          export: true,
          moduleType: 'ModuleId',
          sort: 'SortCode',
          order: 'ASC',
          search: '',
        }
        const data = await WHGetPageData(params)
        if (data.data.rows && data.data.rows.length > 0) {
          data.data.rows.map((item) => {
            item.value = item.FullName
          })
        }
        this.WHdata = data.data.rows
      },
      submit() {
        if (this.status === 1 || this.status === 2) {
          const messages =
            this.status === 1
              ? '单据审核中，不允许修改！'
              : '单据已审核，不允许修改'
          this.$message({
            message: messages,
            type: 'warning',
          })
          return
        }
        if (this.submitType === 'add') {
          this.AddOutboundBill()
        } else {
          this.updataSaveList()
        }
      },
      closeFn() {
        this.enabled = 0
        this.form.WorkFlowID = ''
      },
      exportFn() {
        if(this.selectArr.length<=0){
          this.$message({
            message: translate('请选择要导出的单据'),
            type: 'warning',
          })
          return
        }else {
          this.$confirm(translate('确认导出选中的单据吗?'), translate('提示'), {
          confirmButtonText: translate('确定'),
          cancelButtonText: translate('取消'),
          type: 'warning',
        })
          .then(() => {
            console.log(this.selectArr)
            this.loading = true
            this.download()
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: translate('已取消导出'),
            })
          })
        }
      },
        // 下载物资表
        async download() {
        const formIdArr = []
        this.selectArr.map((item,index) =>{
             formIdArr.push(
              {
                keyValue: item.OBMId,
              }
             )
        })
        const params = formIdArr
        const data = await ExportOutBill(params)
        const time = parseTime(new Date().getTime(), '{y}{m}{d}{h}{i}{s}')
        const blob = new Blob([data])
        const url = URL.createObjectURL(blob)
        const link = document.createElement('a')
        this.loading = false
        link.download = `${this.selectArr[0].Code}${time}.xlsx`
        link.href = url
        link.click()
      },
      async detailFn(row) {
        this.deleList = []
        this.form = row
        this.OBMId = row.OBMId
        this.submitType = 'edit'
        await this.getinstances(row)
        await this.OutboundBillDetail()
        await this.agreePageData()
        await this.pickOrderDatas()
        this.dialogVisible = true
        console.log(this.form)
      },
      async getinstances(row) {
        const params = {
          code: 'Wms_OutboundBillMaster',
          formId: row.OBMId,
        }
        const data = await getinstance(params)
        if (data.code === '200') {
          this.status = data.data?.data?.status
        }
      },
      async OutboundBillDetail() {
        const params = {
          pageNo: 1,
          pageSize: 100,
          total: 0,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: this.OBMId,
        }
        const data = await OutboundBillDetail(params)
        if (data.master) {
          this.$nextTick(() => {
            this.chileddetail = data.rows
            console.log(this.chileddetail)
          })
        }
        if(data.msg) {
          this.$message({
            message: data.msg,
            type: 'warning',
          })
        }
        console.log(data)
      },
      async pickOrderDatas() {
        this.wheres = ''
        if (this.searchInfo || this.searchInfo1 || (this.searchInfo2 && this.searchInfo2 != [] && this.searchInfo2 != null && this.searchInfo2 !='null')) {
          const arr = []
          this.searchInfo.trim() !== '' &&
            arr.push({
              name: 'POUnit',
              value: this.searchInfo,
              displayType: 'like',
            })
          this.searchInfo1.trim() !== '' &&
            arr.push({
              name: 'Code',
              value: this.searchInfo1,
              displayType: 'like',
            })
            this.searchInfo2 &&
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo2!=null ? this.searchInfo2[0]+' 00:00:00':'',
              displayType: 'ThanOrEqual',
            })
            arr.push({
              name: 'CreateDate',
              value: this.searchInfo2!=null ? this.searchInfo2[1]+' 23:59:59':'',
              displayType: 'LessOrequal',
            })
          this.wheres = JSON.stringify(arr)
        }
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: this.wheres,
          export: false,
          value: '',
        }
        const data = await pickOrderData(params)
        this.pickOrderDataList = data.data.rows
      },
      async agreePageData() {
        const params = {
          pageNo: this.pageNo,
          pageSize: this.pageSize,
          tableName: '',
          sort: '',
          order: '',
          wheres: '',
          export: true,
          value: '',
        }
        const data = await agreePageData(params)
        this.agreementList = data.data.rows
      },
      async AddOutboundBill() {
        this.isclick = true
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: [],
        }
        const data = await AddOutboundBill(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
        setTimeout(() => {
          this.isclick = false
        }, 5000)
      },
      async updataSaveList() {
        const params = {
          mainData: this.form,
          detailData: this.chileddetail,
          delKeys: this.deleList,
        }
        const data = await UpdateOutboundBill(params)
        if (data.code == '200') {
          this.getList()
          this.$message({
            message: translate('保存成功'),
            type: 'success',
          })
          this.dialogVisible = false
        }
      },
    },
  })
</script>
<style lang="scss" scoped>
  .flowpath-container {
    .color_494949 {
      display: inline-block;
      width: 70px;
      color: #494949;
      text-align: right;
    }
    .w192 {
      width: 192px;
    }
    .mb20 {
      margin-bottom: 20px;
    }
    .mr10 {
      margin-right: 10px;
    }
    .ml10 {
      margin-left: 10px;
    }
    .mt10 {
      margin-top: 10px;
    }
    .w164 {
      width: 164px;
    }
    .add {
      margin-bottom: 10px;
      text-align: left;
    }
    .iconcommon {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: blue;
    }
    .iconcommon2 {
      position: absolute;
      top: 80px;
      right: 70px;
      font-size: 60px;
      color: red;
    }
    .ml-upload {
      display: inline-block;
      margin-left: 10px;
      vertical-align: bottom;
      margin-right: 10px;
    }
    .iconcolor {
      color: #409eff;
    }
    .color_l {
      color: #67c23a;
    }
    .color_red {
      color: #f56c6c;
    }
  }
</style>
